//
//  API_@MainActor_Demo1VC.swift
//  APSwift
//
//  Created by jianbo.pei on 2024/8/19.
//

import UIKit

class API__MainActor_Demo1VC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        let imageV1 = UIImageView(frame: CGRect(x: 10, y: 200, width: 300, height: 100))
        view.addSubview(imageV1)
        imageV1.contentMode = .scaleAspectFill
        
        guard let url = URL(string: "https://img2.baidu.co0m/it/u=1028011339,1319212411&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1724173200&t=59d9626180b581c872a3a2d186f2d1cd123") else { return }
//        fetchImage(for: url) { result in
//            switch result {
//            case .success(let success):
//                debugPrint("@MainActor - image is \(success)")
//                imageV1.image = success
//            case .failure(let failure):
//                debugPrint("@MainActor - error is \(failure)")
//            }
//        }
        
        let imageV2 = UIImageView(frame: CGRect(x: 10, y: 350, width: 300, height: 100))
        view.addSubview(imageV2)
        imageV2.contentMode = .scaleAspectFill
        Task {
            do {
                let image = try await fetchImage(for: url)
                imageV2.image = image
            } catch {
                print("@MainActor - Failed to fetch image: \(error)")
            }
        }
    }
    
    

}

extension API__MainActor_Demo1VC {
    
    func fetchImage(for url: URL, completion: @escaping (Result<UIImage, Error>) -> Void) {
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data, let image = UIImage(data: data) else {
                DispatchQueue.main.async {
                    completion(.failure(ImageFetchingError.imageDecodingFailed))
                }
                return
            }

            DispatchQueue.main.async {
                completion(.success(image))
            }
        }.resume()
    }
    
    
    @MainActor
    func fetchImage(for url: URL) async throws -> UIImage {
        let (data, _) = try await URLSession.shared.data(from: url)
        guard let image = UIImage(data: data) else {
            throw ImageFetchingError.imageDecodingFailed
        }
        return image
    }

    enum ImageFetchingError: Error {
        case imageDecodingFailed
        case invalidURL
        case networkError(Error)
    }
}
